<?php

namespace fakis\core\web;

use fakis\core\app\AppTrait;
use Yii;
use yii\base\Module;
use yii\helpers\Url;

/**
 * 应用模块
 *
 * @property string $aliasId
 *
 * @author Fakis <fakis738@qq.com>
 */
class AppModule extends Module
{
    use AppTrait;

    const EVENT_BEFORE_INSTANCE = 'beforeInstance';

    const EVENT_AFTER_INSTANCE = 'afterInstance';

    const STATE_INSTANCE = 1;
    const STATE_ENTRY = 2;
    const STATE_END = 3;

    /**
     * 应用Logo
     * @var string
     */
    public $logo;

    /**
     * 应用描述
     * @var string
     */
//    public $description = '你可以通过音视频通知、群聊、朋友圈来和朋友们分享生活，可以通过公众号、视频号获得文章、视频内容，以及通过小程序方便地使用生活服务，还可以开启「关怀模式」，文字与按钮更大更清晰。';
    public $description;

    /**
     * 是否开启调试模式
     * @var bool
     */
    public $debug = false;

    /**
     * 开启应用模块指向路由自动跳转
     * @var bool
     */
    public $enableRouteRediect = false;

    /**
     * 应用模块绑定指定域名
     * @var string
     */
    public $domain;

    /**
     * 配置文件路径
     * @var string
     */
    public $configFilePath;

    /**
     * 应用模块别名
     * @var string
     */
    private $_aliasId;

    /**
     * 返回应用模块别名
     * @return string
     */
    public function getAliasId()
    {
        return $this->_aliasId ?? $this->id;
    }

    /**
     * 设置应用模块别名
     */
    public function setAliasId($alias)
    {
        $this->_aliasId = $alias;
    }

    /**
     * @inheritDoc
     */
    public function beforeAction($action)
    {
        if (($url = $this->routeRedirectUrl()) !== null) {
            Yii::$app->response->redirect($url, 301)->send();
            exit;
        }

        return parent::beforeAction($action);
    }

    /**
     * 实现应用指向路由自动跳转链接
     * @return string|null
     * @throws \yii\base\InvalidConfigException
     */
    public function routeRedirectUrl()
    {
        $id = $this->id;
        $alias = $this->getAliasId();
        $url = Yii::$app->request->getUrl();
        $pattern = "/^\/{$id}(\/.+)*$/i";

        if (
            $this->enableRouteRediect
            && $alias !== null && $alias !== $id
            && preg_match($pattern, $url)
        ) {
            if (!Url::isRelative($this->domain)) {
                return rtrim($this->domain, '/') . preg_replace($pattern, "$1", $url);
            }
            return preg_replace($pattern, "/{$alias}$1", $url);
        }

        return null;
    }

    /**
     * 实例化应用模块
     */
    public function instance()
    {
        $this->state = self::STATE_INSTANCE;
        $configFilePath = $this->configFilePath ? Yii::getAlias($this->configFilePath) : $this->basePath . '/config.php';
        if (file_exists($configFilePath)) {
            $config = require $configFilePath;
            $this->configure($config);
        }
    }

    /**
     * 载入应用模块配置
     * @param array $config
     */
    public function configure(array $config = [])
    {
        Yii::configure($this, $config);
    }
}